<?php
# +--------------------------------------------------------
# |Description: 中直商城对接接口：商品处理类
# +--------------------------------------------------------
# |Company: 北京申合信科技发展有限公司
# +--------------------------------------------------------
# |WebSite: www.shenhexin.com
# +--------------------------------------------------------
# |Author: Akon<18363851918@163.com>
# +--------------------------------------------------------
# |Date: 2017年6月29日
# +--------------------------------------------------------

namespace Zapi\Controller;
use Think\Controller;

class ProductController extends Controller {

    /**
     * 获取品目池接口
     * URL http://api.shenhexin.com/zapi/product/getCategory?token=7d64eb26b98b0afa54922f8f4ff97ce3_1500000255
     * METHOD POST
     * 1、获取access_token
     * 2、校验access_token，若过期，则重新获取
     * 3、获取商品分类数据，以sdb_members表中的cate_type为标志，为1，代表为中直商城api
     */
    public function getCategory(){
        $token = I('get.token');
        A('Common')->checkAccessToken($token);

        $sql = "SELECT cat_name categoryName,cat_id categoryId,api_parent_id categoryParentId FROM sdb_goods_cat WHERE cate_type=1";
        $info = M('','','DB_CONFIG2')->query($sql);
        foreach($info as $key=>$val){
            $cates[$key]['categoryName'] = $val['categoryname'];
            $cates[$key]['categoryId'] = $val['categoryid'];
            $cates[$key]['categoryParentId'] = $val['categoryparentid'];
        }
        if(!$info){
            $res = array(
                'error' => '品目池获取失败，请检查参数是否正确'
            );
            exit(json_encode($res,JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES));
        }
        $res = array(
            "getCategory" => array(
                "success" => $cates
            )
        );

         exit(json_encode($res,JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES));
    }

    /**
     * 获取商品池接口
     * URL http://api.shenhexin.com/zapi/product/getSkus?token=7d64eb26b98b0afa54922f8f4ff97ce3_1500000255
     * METHOD POST
     * 1、获取access_token,catalog_id
     * 2、校验access_token，若过期，则重新获取
     * 3、通过catalog_id获取商品sku
     * {"queryProdPool":{"categoryId":"295"}}
     */
    public function getSkus(){
        $receive = json_decode(file_get_contents('php://input'),true);
        $token = I('get.token');
        A('Common')->checkAccessToken($token);                                         //校验access_token是否合法
        A('Common')->errorMsg($receive['queryProdPool']['categoryId'],'error catalog_id');                     //校验catalog_id是否合法

        $sku_info = M('goods','sdb_','DB_CONFIG2')->where(array('cat_id'=>intval($receive['queryProdPool']['categoryId'])))->field('bn,intro,brand')->select();
        if(!$sku_info){
            $res = array(
                'error' => '没有数据'
            );
            exit(json_encode($res,JSON_UNESCAPED_SLASHES|JSON_UNESCAPED_UNICODE));
        }
        $sku = array();
        foreach($sku_info as $key=>$value){
            $sku_info[$key]['intro'] = htmlspecialchars($value['intro']);
            if(strlen($sku_info[$key]['intro']) < 20) break;                                    //屏蔽掉没有详情图的商品sku
            if(empty($sku_info[$key]['brand'])) break;                                          //屏蔽掉没有品牌的商品sku
            $sku[$key]['skuId'] = $value['bn'];
            $sku[$key]['cmmdtyType'] = 1;
        }
        $res = array(
            'queryProdPool' => array(
                'success' => $sku
            )
        );
        echo json_encode($res,JSON_UNESCAPED_UNICODE);
    }

    /**
     * 商品详情接口
     * URL http://api.shenhexin.com/zapi/product/getDetail?token=7d64eb26b98b0afa54922f8f4ff97ce3_1500000255
     * METHOD POST
     * 1、获取access_token，sku
     * 2、校验access_token，若过期，则重新获取
     * 3、通过sku获取商品详情，只支持单个查询
     * {"getProdDetail":{"skuId":"G57C683B44A8FA"}}
     */
    public function getDetail(){
        $receive = json_decode(file_get_contents('php://input'),true);
        $token = I('get.token');
        A('Common')->checkAccessToken($token);            //校验access_token是否合法
        A('Common')->errorMsg($receive['getProdDetail']['skuId'],'error sku');                //校验sku是否合法

        $query      = "SELECT bn,big_pic,marketable,brand,name,intro
                      FROM sdb_goods
                      where bn='{$receive['getProdDetail']['skuId']}'";
        $info = M('','','DB_CONFIG2')->query($query);
	if(!$info){
	    $res = array(
		'error' => '没有数据'
	    );
	    exit(json_encode($res,JSON_UNESCAPED_SLASHES|JSON_UNESCAPED_UNICODE));
	}
        $tempArr = $info[0];

        $params = array(
            0 => array(
                'desc' => '',          //主参数描述
                'param' => array(
                    array(
                        'snparameterCode' => '',
                        'snparameterSequence' => '',
                        'snparameterdesc' => '',
                        'snparameterVal' => '',
                        'snparametersCode' => '',
                        'snparametersDesc' => '',
                        'snsequence' => '',
                        'coreFlag' => ''
                    )
                )
            )
        );
        foreach($tempArr as $key=>$val){
            $details['skuId'] = $tempArr['bn'];
            $details['image'] = $tempArr['big_pic'];
            $details['brand'] = $tempArr['brand'];
            $details['name'] = $tempArr['name'];
            if($tempArr['marketable'] == 'true'){
                $details['state'] = 1;
            }elseif($tempArr['marketable'] == 'false'){
                $details['state'] = 0;
            }
            $details['introduction'] = $tempArr['intro'];
        }
        $details['prodParams'] = $params;
	$details['saleUnit'] = '';
	$details['category'] = '';
	$details['model'] = '';
	$details['npc'] = '';
	$details['weight'] = '';
        //处理数据
        $details['image']   = "http://www.shenhexin.com/".explode('|',$details['image'])[0];
        $res = array(
            'getProdDetail'  => $details
        );
        echo json_encode($res,JSON_UNESCAPED_SLASHES|JSON_UNESCAPED_UNICODE);
    }

    /**
     * 获取商品图片
     * URL http://api.shenhexin.com/zapi/product/getImages?token=7d64eb26b98b0afa54922f8f4ff97ce3_1500000255
     * METHOD POST
     * 1、获取access_token，sku
     * 2、校验access_token，若过期，则重新获取
     * 3、sku支持批量传入
     */
    public function getImages() {
        $receive = json_decode(file_get_contents('php://input'),true);
        $token = I('get.token');
        A('Common')->checkAccessToken($token);

        $skuStr = addApostropheToString(implode(',',changeKey($receive['skuIds'],'skuId')));
        $sql = 'SELECT a.bn skuid,a.big_pic main_path,b.big other_path FROM sdb_goods a JOIN sdb_gimages b ON a.goods_id=b.goods_id WHERE a.bn IN ('."{$skuStr}".')';
        $info = M('','','DB_CONFIG2')->query($sql);

        foreach($info as $key=>$val){
            $temp_1[$val['skuid']][] =  'http://www.shenhexin.com/' . explode('|',$val['main_path'])[0];
            $temp_1[$val['skuid']][] = 'http://www.shenhexin.com/' . explode('|',$val['other_path'])[0];
        }
        foreach($temp_1 as $key=>$val){
            $temp_2[$key] = array_values(array_unique($temp_1[$key]));
        }
        foreach($temp_2 as $key=>$val){
            foreach($val as $k=>$v){
                if($k === 0){
                    $images[$key]['urls'][$k]['primary'] = 1;
                    $images[$key]['urls'][$k]['path'] = $v;
                }else{
                    $images[$key]['urls'][$k]['primary'] = 0;
                    $images[$key]['urls'][$k]['path'] = $v;
                }
            }
            $images[$key]['skuId'] = $key;
        }
        $res = array(
            "queryProdImage" => array(
                "success" => array_values($images)
            )
        );
        echo json_encode($res,JSON_UNESCAPED_SLASHES|JSON_UNESCAPED_UNICODE);
    }


    /**
     * 上下架状态接口
     * URL http://api.shenhexin.com/zapi/product/getState?token=7d64eb26b98b0afa54922f8f4ff97ce3_1500000255
     * METHOD POST
     * 1、获取access_token，sku
     * 2、校验access_token，若过期，则重新获取
     * 3、通过sku获取上下架状态，支持批量查询
     */
    public function getState(){
        $receive = json_decode(file_get_contents('php://input'),true);
        $token = I('get.token');

        A('Common')->checkAccessToken($token);                 //校验access_token是否合法

        $skuStr = addApostropheToString(implode(',',changeKey($receive['skuIds'],'skuId')));
        $sql   = 'select bn sku,marketable state from sdb_goods where bn in ('."{$skuStr}".')';
        $info = M('','','DB_CONFIG2')->query($sql);

        foreach($info as $key=>$val){
            if($val['state'] == 'true'){
                $states[$key]['skuId'] = $val['sku'];
                $states[$key]['state'] = 1;
            }else if($val['state'] == 'false'){
                $states[$key]['skuId'] = $val['sku'];
                $states[$key]['state'] = 0;
            }
        }

        $res = array(
            "onShelvesList" => array(
                "success" => $states
            )
        );
        echo json_encode($res,JSON_UNESCAPED_UNICODE);
    }


    /**
     * 批量查询商品价格接口
     * URL http://api.shenhexin.com/zapi/product/getPrices?token=7d64eb26b98b0afa54922f8f4ff97ce3_1500000255
     * METHOD POST
     * 1、获取access_token，sku
     * 2、校验access_token,若过期，则重新获取
     * 3、通过sku获取商品价格，sku支持批量
     */
    public function getPrices(){
        $receive = json_decode(file_get_contents('php://input'),true);
        $token = I('get.token');
        A('Common')->checkAccessToken($token);                                                                  //校验access_token是否合法

        $sku_str = addApostropheToString(implode(',',changeKey($receive['queryPrice']['skus'],'skuId')));                         //单个字符添加单引号
        $sql = 'SELECT a.price,a.bn sku,b.discount FROM sdb_goods a JOIN sdb_goods_cat b ON a.cat_id = b.cat_id WHERE a.bn IN('.$sku_str.')';
        $goods_prices = M('','','DB_CONFIG2')->query($sql);
	if(!$goods_prices){
	    $res = array(
		'error' => '没有数据'
	    );
	    exit(json_encode($res,JSON_UNESCAPED|SLASHES|JSON_UNESCAPED_UNICODE));
	}
        foreach($goods_prices as $key=>$val){
            $goods_prices[$key]['skuId'] = $val['sku'];
            $goods_prices[$key]['price'] = sprintf('%.2f',$val['price'] * $val['discount']);
	    $goods_prices[$key]['discountRate'] = $val['discount'];
            $goods_prices[$key]['rfPrice'] = $val['price'];
            unset($goods_prices[$key]['sku']);
            unset($goods_prices[$key]['discount']);
        }
        $res = array(
            "queryPrice" => array(
                "success" => $goods_prices
            )
        );
        $this->ajaxReturn($res);
    }

    /**
     * 多商品的精准库存查询接口
     * URL http://api.shenhexin.com/zapi/product/getStockState?token=7d64eb26b98b0afa54922f8f4ff97ce3_1500000255
     * METHOD POST
     * 1、获取access_token，sku
     * 2、校验access_token,若过期，则重新获取
     * 3、通过sku获取商品价格，sku支持批量
     */
    public function getStockState() {
        $receive = json_decode(file_get_contents('php://input'),true);
        $token = I('get.token');
        A('Common')->checkAccessToken($token);                                                                  //校验access_token是否合法
        foreach($receive['queryMpStock']['skuIds'] as $key=>$val){
            $skus[$key] = $val['skuId'];
        }
        $sku_str = addApostropheToString(implode(',',$skus));

        $sql = 'SELECT bn,store FROM sdb_goods WHERE bn IN ('."{$sku_str}".')';
        $info = M('','','DB_CONFIG2')->query($sql);

        foreach($receive['queryMpStock']['skuIds'] as $key=>$val){
            $receiveSku[$val['skuId']] = $val;
        }
        
        foreach($info as $key=>$val){
            $info[$key]['skuId'] = $val['bn'];
            if($val['store'] == 0) {
                $info[$key]['state'] = '03';
            }else{
                if($val['store'] >= $receiveSku[$val['bn']]['num']){
                    $info[$key]['state'] = '00';
                }elseif($val['store'] <= $receiveSku[$val['bn']]['num']){
                    $info[$key]['state'] = '03';
                }
            }
            unset($info[$key]['store']);
            unset($info[$key]['bn']);
        }

        $res = array(
            'queryMpStock' => array(
                'success' => $info
            )
        );
        $this->ajaxReturn($res);
    }

}
